<?php

namespace App\Enums;

use Exception;
use ReflectionClass;
use ReflectionProperty;

/**
 * @author Green Leaf <786407418@qq.com>
 * @description 错误码基类
 */
class ErrorCode
{
    /************************************************************
     ************************************************************
     ************************************************************
     *
     * 使用trait特性自定义错误类 并在当前类的子类进行use {child}Trait
     *
     ************************************************************
     ************************************************************
     ************************************************************/


    const ERROR_TITLE = "错误码 【 %s 】注释信息未配置";
    const DOCUMENT_MESSAGE_FIELD = "message";


    /**
     * 获取错误信息
     *
     * @param int $code  错误码
     * @param string $default 默认错误信息
     * @return string
     */
    public static function getMessage(int $code, string $default = ""): string
    {
        $re = new ReflectionClass(new static());

        $actuallyProperty = null;
        foreach ($re->getProperties(ReflectionProperty::IS_STATIC) as $property) {
            if ($code == $property->getValue()) {
                $actuallyProperty = $property;
                break;
            }
        }

        if ($actuallyProperty instanceof ReflectionProperty) {
            preg_match_all(
                '/(@([a-zA-Z]+)[\s]*([\S]+))/',
                $actuallyProperty->getDocComment(),
                $matches
            );

            $documents = convertPregMatchToArr($matches);
            return empty($documents[self::DOCUMENT_MESSAGE_FIELD]) ? $default : $documents[self::DOCUMENT_MESSAGE_FIELD];
        }else{
            logException(sprintf(self::ERROR_TITLE, $code), new Exception(), ["code" => $code], true);
            return $default;
        }
    }

}
